package event

import (
	"iot-base/common/cache"
	"iot-base/common/dbconn"
	"iot-base/common/notify"

	"iot-base/common/config"
	"iot-base/common/eventtype"
	"iot-base/common/logger"
)

var eventChan chan *eventtype.Event

//SetEventChan 设置事件
func SetEventChan(eventSet chan *eventtype.Event) {
	eventChan = eventSet
}

func init() {
	dbconn.DBConnection.AutoMigrate(&eventtype.Event{})
	if config.DBOption.Type == "postgres" && config.PType == "cloud" {
		dbconn.DBConnection.Exec(`CREATE EXTENSION IF NOT EXISTS timescaledb CASCADE;`)
		//dbconn.DBConnection.Exec(`SELECT create_hypertable('RealData', 'pick_time';`)
		//dbconn.DBConnection.Exec(`SELECT create_hypertable('RealData', 'pick_time',chunk_time_interval => 86400000000);`)
		dbconn.DBConnection.Exec(`SELECT create_hypertable('events', 'time',chunk_time_interval => interval '7 day');`)

	}
	notify.SubRawEvent(func(pEvent *eventtype.Event) {
		pThing, _ := cache.GetThing(pEvent.TID)
		if pThing == nil {
			logger.SLog.Error("event thing not found", pEvent.TID)
			return
		}
		modelID := pThing.Thing.ModelID
		if pEvent.EventID == "online" || pEvent.EventID == "offline" {
			pEvent.Level = 2
			if pEvent.EventID == "online" {
				pEvent.EventName = "上线"
			} else {
				pEvent.EventName = "离线"
			}

		} else {
			_, pInfo := cache.GetEventInfo(modelID, pEvent.EventID)
			if pInfo == nil {
				logger.SLog.Error("event eventInfo not found", pEvent.TID, pEvent.EventID)
				return
			}
			pEvent.Level = pInfo.Level
		}

		pEvent.StationID = pThing.StationID
		pEvent.StationName = pThing.GetStationName()

		pEvent.ToDBObj()
		var err error
		if !pEvent.IsNotSaveDB {
			err = dbconn.DBConnection.Create(pEvent).Error
		}

		if err == nil {
			notify.PubMsg(false, "event", pEvent)
			if eventChan != nil {
				eventChan <- pEvent
			}
		}

	})

}
